package com.company.practice;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * volitale 保证可见性和不保证原子性的例子
 */

public class Test5 {


    public static void main(String[] args) throws InterruptedException {
        //canSee();

        //cantAtomic();


    }

    private static void cantAtomic() {
        T t2 = new T();
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    t2.addPlusPlus();
                }
            },String.valueOf(i)).start();
        }
        //除了gc线程和main线程，还有上面的线程没执完，就等等
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+": "+t2.i2);
    }


    private static void canSee() {
        T tt = new T();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            tt.addI();
            System.out.println(Thread.currentThread().getName()+": "+tt.i);
        },"t1").start();

        while (tt.i == 1) {
            // 如果可见性没有，这里main线程会无限循环
        }
        System.out.println(Thread.currentThread().getName()+": "+tt.i);
    }
}


class T{
    //int i = 1;
    volatile int i = 1;

    AtomicInteger i2 = new AtomicInteger(0);

    public void addI(){
        this.i = 10;
    }




    public void addPlusPlus(){
        this.i2.getAndIncrement();
    }
}